package com.user.web;

import com.user.entity.Role;
import com.user.entity.UserInfo;
import com.user.util.JsonUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/security")
public class SecurityController {
    @RequestMapping("/getUser")
    public String getLogin(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> grantedAuthorities = authentication.getAuthorities();
        Set<Role> authorities = grantedAuthorities.stream().map(item -> {
            return new Role(item.getAuthority());
        }).collect(Collectors.toSet());
        Long principal =(Long)authentication.getPrincipal();
        String credentials = (String)authentication.getCredentials();
        UserInfo userInfo = new UserInfo();
        userInfo.setId(principal);
        userInfo.setUsername(credentials);
        userInfo.setGrantedAuthorities(authorities);
        return JsonUtils.toString(userInfo);
    }
}
